const sqlite3 = require('../app/backend/node_modules/sqlite3').verbose();
const db = new sqlite3.Database('../app/backend/data/pph.sqlite');

console.log('🔍 调试节拍字段显示问题...');
console.log('=====================================');

async function debugTaktDisplay() {
  return new Promise((resolve, reject) => {
    // 1. 检查A0101150004的最新数据
    console.log('📊 检查A0101150004的最新记录:');
    db.all(`SELECT record_date, line_name, is_whole_machine, 
                   target_takt_time, target_motor_takt_time,
                   CASE 
                     WHEN is_whole_machine = 1 THEN target_takt_time 
                     ELSE target_motor_takt_time 
                   END as should_display_takt,
                   calculated_pph, target_pph, estimate_pph
            FROM pph_records 
            WHERE material_code = 'A0101150004' 
            AND record_date >= '2025-09-18'
            ORDER BY record_date DESC, line_name LIMIT 10`, (err, records) => {
      if (err) {
        console.error('❌ 查询失败:', err);
        return reject(err);
      }
      
      console.log('📋 A0101150004最新记录:');
      console.table(records);
      
      // 2. 检查目标值配置
      console.log('\n🎯 检查A0101150004的目标值配置:');
      db.all(`SELECT material_code, line_name, record_date, 
                     takt_time, motor_takt_time, 
                     whole_machine_target, motor_target,
                     is_active
              FROM pph_targets 
              WHERE material_code = 'A0101150004' 
              AND is_active = 1
              ORDER BY record_date DESC, line_name LIMIT 5`, (err2, targets) => {
        if (err2) {
          console.error('❌ 目标值查询失败:', err2);
          return reject(err2);
        }
        
        console.log('📊 目标值配置:');
        console.table(targets);
        
        // 3. 分析问题
        console.log('\n🔍 问题分析:');
        
        const hasTargetTakt = records.some(r => r.target_takt_time !== null);
        const hasMotorTakt = records.some(r => r.target_motor_takt_time !== null);
        const hasTargetConfig = targets.length > 0;
        
        console.log(`- 记录中有整机节拍: ${hasTargetTakt}`);
        console.log(`- 记录中有电机节拍: ${hasMotorTakt}`);
        console.log(`- 目标值配置存在: ${hasTargetConfig}`);
        
        if (!hasTargetConfig) {
          console.log('❌ 问题1: 目标值表中没有A0101150004的配置');
          console.log('💡 解决方案: 在目标值管理中为A0101150004配置节拍值');
        }
        
        if (hasTargetConfig && !hasTargetTakt && !hasMotorTakt) {
          console.log('❌ 问题2: 重算没有正确获取节拍值');
          console.log('💡 解决方案: 检查重算逻辑或重新执行重算');
        }
        
        // 4. 检查前端显示逻辑
        console.log('\n🖥️ 前端显示分析:');
        records.forEach((record, index) => {
          const shouldShow = record.should_display_takt;
          const actualShow = record.is_whole_machine === 1 ? record.target_takt_time : record.target_motor_takt_time;
          
          console.log(`记录${index + 1}: ${record.line_name}号线 ${record.record_date}`);
          console.log(`  - 生产类型: ${record.is_whole_machine === 1 ? '整机' : '电机'}`);
          console.log(`  - 应显示节拍: ${shouldShow || '无'}`);
          console.log(`  - 前端会显示: ${actualShow || '-'}`);
          console.log(`  - 显示正确: ${shouldShow === actualShow ? '✅' : '❌'}`);
        });
        
        // 5. 生成修复建议
        console.log('\n🔧 修复建议:');
        
        if (!hasTargetConfig) {
          console.log('1. 在目标值管理中为A0101150004配置节拍值');
          console.log('   - 如果是电机生产，配置"电机节拍"字段');
          console.log('   - 如果是整机生产，配置"节拍"字段');
        }
        
        if (hasTargetConfig && (!hasTargetTakt && !hasMotorTakt)) {
          console.log('2. 重新执行重算任务');
          console.log('   - 确保服务器代码已更新');
          console.log('   - 重启后端服务');
          console.log('   - 执行重算API');
        }
        
        // 检查是否需要前端修复
        const needsFrontendFix = records.some(r => {
          const shouldShow = r.should_display_takt;
          const actualShow = r.is_whole_machine === 1 ? r.target_takt_time : r.target_motor_takt_time;
          return shouldShow !== actualShow && shouldShow !== null;
        });
        
        if (needsFrontendFix) {
          console.log('3. 前端显示逻辑需要优化');
          console.log('   - 当前前端分别显示"节拍"和"整机节拍"两列');
          console.log('   - 建议合并为一个"节拍"列，根据生产类型智能显示');
        }
        
        db.close();
        resolve({
          records,
          targets,
          hasTargetTakt,
          hasMotorTakt,
          hasTargetConfig,
          needsFrontendFix
        });
      });
    });
  });
}

// 执行调试
debugTaktDisplay().catch(err => {
  console.error('❌ 调试失败:', err);
  process.exit(1);
});
